﻿$(document).ready(
    function() {
        //状态
        var allStatus=[],statusContext=$('.meeting_tips'),caller,telephone,allMembers,callerCurrentStatus='NEW',canOperation=true,
		meet=$('.meeting_coming'),loadPrompt,
        status = {
            'NEW': ['呼叫中<a class="dotting"></a>', 'begin','正在呼叫name(tel)'],
            'INVITE': ['呼叫中<a class="dotting"></a>', 'begin','正在呼叫name(tel)'],
            'RINGING': ['响铃中<a class="dotting"></a>', 'begin','正在呼叫name(tel)'],
            'ANSWERED': ['通话中<a class="dotting"></a>', 'begin','name(tel)已接听'],
            'DISCONNECTED': ['挂断', 'end','name(tel)已挂断'],
            'FAILED': ['挂断', 'end','name(tel)已退出会议'],
            'CANCEL': ['挂断', 'end','name(tel)取消呼叫']
        };
		
		function statusChanged(){
			statusContext.html(allStatus.join('<br>')+'<span class="dotting"></span>');
			setTimeout(function(){
				statusContext.scrollTop(statusContext[0].scrollHeight);
			},10);
		}
		
		function findNumberObject(tel){
			var set=$('.meeting_coming').find('dl');
			for(var i=0;i<set.length;i++){
				if(set[i].id.indexOf(tel)>-1)
					return $(set[i]);
			}
		}
		
		function add(number,type){
			if(type=='new'){
	            meet.append("<dl id='"+number+"'><dt><h2>"+number+"</h2><span class='green'>准备呼叫<a class='dotting'></a></span><input type='hidden' value='NEW'></dt><dd style='background-color:#a5a5a5'>挂断</dd></dl>");
			}else{
                $('#'+number).find('dt span').attr('class','').html('准备重拨<a class="dotting"></a>');
                $('#'+number).find('dd').css('background','#a5a5a5').text('挂断');
			}	
            $('#meeting_add').val('');
		}
		
        //会议中添加人员
        function conferenceAdd(session_id,number,type){
            $.ajax({
                type : "post",  
                dataType : "jsonp",
                url : abilityUrl+"/MPTYv4/conferenceAdd.do",
                async : true,
                data : {
                    'sessionid' : session_id,
                    'called' : number
                },
                success : function(data) {
                    if(data['result']=='0'){
                        if(type=='new'){
                            //写入被叫人信息
//                            meet.append("<dl id='"+number+"'><dt><h2>"+number+"</h2><span class='green'>呼叫中<a class='dotting'></a></span><input type='hidden' value='NEW'></dt><dd>挂断</dd></dl>");
//                            $('#meeting_add').val('');		
                        	$('#'+number).find('span').html("呼叫中<a class='dotting'></a>");
                            $('#'+number).find('dd').removeAttr('style');                    	
                        }else{
//                            $('#'+number).find('dt span').attr('class','').html('重拨中<a class="dotting"></a>');
//                            $('#'+number).find('dd').attr('class','').text('挂断');
                        	$('#'+number).find('span').html('重拨中<a class="dotting"></a>');
                            $('#'+number).find('dd').attr('class','').text('挂断');
                        }
                    }else{
                        new UserPrompt("会议中添加人员失败，请稍后再试："+data['describe']);
                    }
                },
                error : function(data) {
                    new UserPrompt("网络连接异常");
                },
                complete : function() {
                    if(type==='old'){
						$('#'+number).find('dd').css('background','#ff5842');
						canOperation=true;
					}
                }
            });
        }
        //会议中踢出人
        function conferenceMinus(session_id,number){
            $.ajax({
                type : "post",
                dataType : "jsonp",
                url : abilityUrl+"/MPTYv4/conferenceMinus.do",
                async : true,
                data : {
                    'sessionid' : session_id,
                    'called' : number
                },
                success : function(data) {
                    if(data['result']=='0'){
                        $('#'+number).find('dt span').attr('class','red').text('踢出');
                        $('#'+number).find('dd').attr('class','bg_green').text('重拨');
                    }else{
                        new UserPrompt("会议中踢出人员失败，请稍后再试："+data['describe']);
                    }
                },
                error : function(data) {
                    new UserPrompt("网络连接异常");
                },
                complete : function() {
					$('#'+number).find('dd').removeAttr('style').addClass('bg_green');
					canOperation=true;
                }
            });
        }
        //结束通话
        function endConference(session_id){
            $.ajax({
                type : "post",
                dataType : "jsonp",
                url : abilityUrl+"/MPTYv4/endConference.do",
                async : true,
                data : {
                    'sessionid' : session_id
                },
                success : function(data) {
                    var jsonData = {};
                    var resultData=[];
                    resultData.push(dataJson[0]);
                    jsonData.data=resultData;
                    location.assign('Launch_meeting.html?data='+JSON.stringify(jsonData));
                },
                error : function(data) {
                },
                complete : function() {
					if(loadPrompt){
						loadPrompt.close();
						loadPrompt=null;
					}
                },
				beforeSend:function(){
					loadPrompt=new LoadPrompt('结束通话...');
				}
            });
        }
        if(!window.localStorage){
            new UserPrompt('您所使用的浏览器版本太低，或不支持本页面，请更换浏览器并重试！');
        }else{
            //查询状态
            var statusUrl = localCache.getSessionItem("statusUrl");
            //使用的域名
            var abilityUrl = localCache.getSessionItem("abilityUrl");

            //设置滚动显示
            var content = $('#content');
            content.css('overflow','auto');
            //获取url中传的值
            var queryString = decodeURI(window.location.search.substr(1));
            //获取data信息
            var dataString=matchQueryString(queryString,"data")||'';
            //转换成json
            var obj=eval(dataString);
            //获取通话session_id
            var session_id=obj[0]['session_id'];
            //获取相关人员信息json
            var dataJson=allMembers=eval(obj[0]['data']),len=dataJson.length;
            for(var i=0;i<len;i++){
                if(i==0){
                    //写入主叫人信息
                    $('.master h3').text((caller=dataJson[i]['name']));
                    $('.master span').text((telephone=dataJson[i]['telephone']));
                }else{
                    //写入被叫人信息
                    meet.append("<dl id='"+dataJson[i]['telephone']+"'><dt><h2>"+dataJson[i]['name']+"</h2><span class=\"green\">呼叫中<a class=\"dotting\"></a></span><input type='hidden' value='NEW'></dt><dd>挂断</dd></dl>");
                }
            }
            //会议中添加人
            $('.meeting_add span').on('click',function(event){  
              event.stopPropagation(); 
				var tel=$('#meeting_add').val(),validateResult;
				if(tel===''){
					new UserPrompt('参会人电话号码不能为空，请重新输入');
					return;
				}
                validateResult=validateNumber(tel);
				if (!validateResult.success) { 
					new UserPrompt(validateResult.msg);
					return;   
				}
				if(tel===telephone){
					new UserPrompt('不能添加主叫进入会议，请重新输入');
					return;
				}
				if(len===10){
					new UserPrompt('最多只能添加9位参会人');
					return;
				}
                //拼传入数据的json
                var tempData=[];
				tempData.push({
					name:tel,
					telephone:tel,
					type:''
				});
                var isNewPhone=true;				
				for(var m=1;m<allMembers.length;m++){
					if(allMembers[m].telephone===tel){
						isNewPhone=false;
						break;
					}
				}
				if(isNewPhone){
					add(tel,'new');
					 //调用添加人接口
                    conferenceAdd(session_id,tel,'new');
					//写入本地存储
					meetCache.addMeetMembers(session_id,tempData);
                    len++;
				}else{
					canOperation=false;
					add(tel,'old');
                    conferenceAdd(session_id,tel,'old');
				}
            });

            //增加各个通话人的操作，包括通话中挂断和挂断状态用户重拨
            $(document.body).on('click','.meeting_coming dd',function() {
				if(!canOperation)
					return;
				canOperation=false;
                var myClass=$(this).attr('class');
                //获取用户电话号码
                var number=$(this).parent().attr('id');
                //判断如果样式为绿色，则说明已挂断，则需要点击重拨
				$(this).css('background','#a5a5a5');
                if(myClass=='bg_green'){
					add(number,'old'); 
                    conferenceAdd(session_id,number,'old');
                }else{
                    //判断如果样式不为绿色，则说明正在通话中，则需要点击挂断
                    conferenceMinus(session_id,number);
                }
            });
            //首先将通话成功标识设置为失败，并存入本地存储
            meetCache.setMeetStatus(session_id,'fail');
            //获取挂机标识次数，如果到达一定次数，自动挂机
            var closeCount=0;
            //定时查询状态
            window.setInterval(function(){
                $.ajax({
                    type: "get",
                    dataType: "jsonp",
                    url: statusUrl,
                    async: true,
                    data: {
                        "sessionid": session_id
                    },
                    success: function (json) {
                        if (json['result'] == '0') {
                            //获取状态信息
                            var dataJson=eval(json['data']);
                            var closeTag=true;  
                            //循环查看当前所有人的状态
                            for(var i=0;i<dataJson.length;i++){
                                //获取相应电话号码
                                var tmp_callee=dataJson[i]['callee'];
                                if(tmp_callee.substring(0,2)=='86'){
                                    tmp_callee=tmp_callee.substring(2);
                                }else if(tmp_callee.substring(0,1)=='0'){
                                    tmp_callee=tmp_callee.substring(1);
                                }
								if(tmp_callee===telephone||telephone.indexOf(tmp_callee)>-1){//主叫状态
									var newStatus=dataJson[i]['call_state'];
									if(callerCurrentStatus!==newStatus){
										if(callerCurrentStatus!=='INVITE'&&newStatus!=='RINGING'){
										   allStatus.push(status[newStatus][2].replace('name',caller).replace('tel',telephone));
										   statusChanged();
										}
										callerCurrentStatus=newStatus;
										if('DISCONNECTED,FAILED,CANCEL'.indexOf(callerCurrentStatus)>-1){//主叫挂断
											 window.clearInterval(timer_task_handler);//取消定时
											 var countdown=3;
											 var timertip=$("#meeting_btn");
											 var intervalId=window.setInterval(function(){
												 if(countdown===0){
								                    var jsonData = {};
								                    var resultData=[];
								                    resultData.push(allMembers[0]);
								                    jsonData.data=resultData;
								                    location.assign('Launch_meeting.html?data='+JSON.stringify(jsonData));
												 }else{
													 timertip.text('会议已经结束，'+(countdown--)+'秒后返回上一页面');
												 }
											 },1000);
										}										
									}  
								}else{//被叫状态
									//获取相应手机号码的对象
									var tmp_callee_object = $('#'+tmp_callee);
									if(tmp_callee_object&&tmp_callee_object.length===0){
										tmp_callee_object=findNumberObject(tmp_callee);
									}
									//判断对象是否存在
									if(tmp_callee_object&&tmp_callee_object.length>0){
										//获取这个手机号码当前的状态
										var tmp_callee_state=tmp_callee_object.find('dt input').val();
										//拿到新的状态
										var tmp_callee_state_new=dataJson[i]['call_state'];
										//判断如果当前用户有正在接听，则不关闭会议，判断标记
										if(status[tmp_callee_state_new][1]=='begin'){
											//如果有一个通话接听，则设置为成功
											meetCache.setMeetStatus(session_id,'success');
											closeTag=false;
											//如果有一个电话未被挂断，则将前面的挂断标识清零
											closeCount=0;
										}
										//判断两个状态是否相同，如果不相同，则更新状态
										if(tmp_callee_state!=tmp_callee_state_new){
											//更新状态
											tmp_callee_object.find('dt input').val(tmp_callee_state_new);
											//变更页面样式
											if(status[tmp_callee_state_new][1]=='begin'){
												tmp_callee_object.find('dt span').attr('class','').html(status[tmp_callee_state_new][0]);
												tmp_callee_object.find('dd').attr('class','').text('挂断');
											}else{
												tmp_callee_object.find('dt span').attr('class','red').html(status[tmp_callee_state_new][0]);
												tmp_callee_object.find('dd').attr('class','bg_green').text('重拨');
											}
											//变更实时状态
											//获取人姓名
											var callee_name=tmp_callee_object.find('dt h2').text();										
											//写入相应状态信息
											if(tmp_callee_state_new==='CANCEL'){//主叫取消呼叫
												allStatus.push(status[tmp_callee_state_new][2].replace('name',caller).replace('tel',telephone));
											}else if(tmp_callee_state!=='INVITE'&&tmp_callee_state_new!='RINGING')//都是发起呼叫，不需要更改状态
												allStatus.push(status[tmp_callee_state_new][2].replace('name',callee_name).replace('tel',tmp_callee));
											statusChanged();
										}
									}
								}
                            }
							/**
                            //如果标记为所有通话都已关闭，则自动调用关闭会议
                            if(closeTag){
                                closeCount++;
                                if(closeCount>20){
                                    //调用结束通话方法
                                    endConference(session_id);
                                }else{
                                    //写入相应状态信息
                                    //statusContext.text('所有通话都已挂断！');
                                }
                            }  **/
                        } else {
                            //statusContext.text("请稍等....");
                        }
                    },
                    complete: function () {
                    }
                });
            },1000);

            // 会议计时
            var timer_task_handler;
            var timeCount = 0;
            window.clearInterval(timer_task_handler);//二次返回页面时清空定时器
            timer_task_handler = window.setInterval(function(){
                timeCount = timeCount + 1;
                var hours = parseInt(timeCount / 3600);// 小时数
                var minutes = parseInt(timeCount / 60);// 分钟数
                if(minutes>=60){
                    minutes=minutes%60;
                }
                var seconds = timeCount % 60;
                if(hours < 10)
                    hours = "0" + hours;
                if(minutes < 10)
                    minutes = "0" + minutes;
                if(seconds < 10)
                    seconds = "0" + seconds;
                $("#meeting_btn").text('结束会议(' + hours + ':' + minutes + ':' + seconds +')');
            },1000);
			
			$(document).on('click','#meeting_btn,#back',function(){
                //调用结束通话方法
                endConference(session_id);
            });
        }

    }
);